package com.yu.blog.controller;

import com.yu.blog.result.Result;
import com.yu.blog.service.LoginService;
import com.yu.blog.utils.CaptchaUtils;
import com.yu.blog.utils.RandomUtils;
import com.yu.blog.utils.RedisUtils.RedisUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@RestController
@RequestMapping("/api")
public class LoginController {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private LoginService loginService;

    @GetMapping("/getCaptcha/{phoneNum}")
    public Result<String> getPhoneCaptcha(@PathVariable("phoneNum") String phoneNum) throws Exception {
        //此处手机号只限于本人手机号能够接收短信。PS:已设置本人手机号为测试号码
        String randomCode = RandomUtils.randomSixCode();
        Boolean success = loginService.getCaptcha(phoneNum, randomCode);
        if (success) {
            redisUtils.set("phoneNum:" + phoneNum, 5 * 60 * 60);
            return Result.success(randomCode);
        } else return Result.failed();
    }

    @GetMapping("/captchaCode")
    public void getRandomCaptchaCode(HttpServletResponse response) throws IOException {
        String randomCode = RandomUtils.randomLetterCode(4);
        //此处多人登陆时，共用一个key，会出现被value被覆盖的情况，后续将会修正
        redisUtils.set("captchaCode", randomCode,60L);
        CaptchaUtils captchaUtils = new CaptchaUtils();
        captchaUtils.CreateImageCode(120, 40, randomCode, 30);
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache");
        captchaUtils.write(response.getOutputStream());
    }

}
